package com.auerdi.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.auerdi.R;
import com.auerdi.event.TabSelectedEvent;
import com.auerdi.ui.account.ADLoginFragment;
import com.auerdi.ui.fragment.a_home.AdHomeTabFragment;
import com.auerdi.ui.fragment.b_classify.AdClassifyTabFragment;
import com.auerdi.ui.fragment.c_officer.ADOfficeTabFragment;
import com.auerdi.ui.fragment.e_my.AdMeTabFragment;
import com.auerdi.ui.fragment.third.WechatThirdTabFragment;
import com.auerdi.ui.view.BottomBar;
import com.auerdi.ui.view.BottomBarTab;
import com.example.eggframe.GoHomeEvent;
import com.example.eggframe.LoginEvent;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.PerProxyinfor;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import es.dmoral.toasty.Toasty;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;
import me.yokeyword.fragmentation.ISupportFragment;
import me.yokeyword.fragmentation.SupportFragment;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by tse on 16/6/30.
 */
public class MainFragment extends SupportFragment {
    private static final int REQ_MSG = 10;

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int Four = 3;
    public static final int Five = 4;


    private SupportFragment[] mFragments = new SupportFragment[4];

    private BottomBar mBottomBar;
    public static Integer isExper = 0;//0 否1 是


    public static MainFragment newInstance() {

        Bundle args = new Bundle();

        MainFragment fragment = new MainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.wechat_fragment_main, container, false);
        initView(view);
//        L.d("hcia", "onCreateView:");

        EventBusActivityScope.getDefault(_mActivity).register(this);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        RetrofitClient.getPDAClient().create(AdService.class).personalISProxy()
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<PerProxyinfor>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<PerProxyinfor> perProxyBOb) {
//                        L.d("hcia", "perProxyBOb.getBody().getProxy():" + perProxyBOb.getBody().getProxy());


                        isExper = perProxyBOb.getBody().getProxy();
//                        L.d("hcia", "isExper:" + isExper);
                        isExper = 1;
//                        isExper = 0;
                    }
                });


        SupportFragment firstFragment = findChildFragment(AdHomeTabFragment.class);
        if (firstFragment == null) {
            mFragments[FIRST] = AdHomeTabFragment.newInstance();
            mFragments[SECOND] = AdClassifyTabFragment.newInstance();
            mFragments[THIRD] = ADOfficeTabFragment.newInstance();
            mFragments[Four] = AdMeTabFragment.newInstance();
//            mFragments[Four] = WechatFirstTabFragment.newInstance();
//            mFragments[Five] = AdMeTabFragment.newInstance();

            loadMultipleRootFragment(R.id.fl_tab_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD],
                    mFragments[Four]
//                    , mFragments[Five]
            );
        } else {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题

            // 这里我们需要拿到mFragments的引用
            mFragments[FIRST] = firstFragment;
            mFragments[SECOND] = findChildFragment(ADOfficeTabFragment.class);
            mFragments[THIRD] = findChildFragment(WechatThirdTabFragment.class);
        }
    }

    private void initView(View view) {
        mBottomBar = (BottomBar) view.findViewById(R.id.bottomBar);


        mBottomBar
                .addItem(new BottomBarTab(_mActivity, R.mipmap.home_n, "首页"))
                .addItem(new BottomBarTab(_mActivity, R.mipmap.class_n, "分类"))
//                .addItem(new BottomBarTab(_mActivity, R.mipmap.cutprice, "体验官") {
//                    @Override
//                    public boolean isCenter() {
//                        return true;
//                    }
//                })
                .addItem(new BottomBarTab(_mActivity, R.mipmap.msg_n, "砍价"))
                .addItem(new BottomBarTab(_mActivity, R.mipmap.user_n, "我的"));

        // 模拟未读消息
//        mBottomBar.getItem(FIRST).setUnreadCount(9);

//        mBottomBar.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

        mBottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {

//                BottomBarTab tab = mBottomBar.getItem(FIRST);
//                if (position == FIRST) {
//                    tab.setUnreadCount(0);
//                } else {
//                    tab.setUnreadCount(tab.getUnreadCount() + 1);
//                }


                showHideFragment(mFragments[position], mFragments[prePosition]);


            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {
                // 在FirstPagerFragment,FirstHomeFragment中接收, 因为是嵌套的Fragment
                // 主要为了交互: 重选tab 如果列表不在顶部则移动到顶部,如果已经在顶部,则刷新

                if (position == 2) {

//                    EventBus.getDefault().post(ADCutHomeFragMent.newInstance());
//                    EventBus.getDefault().post(ADOfficerRigisterFragment.newInstance());

                }


//                if (MainFragment.isExper == 1 && position == 2) {
//                    EventBus.getDefault().post(CDisPostFragment.newInstance());
//
//                }


                EventBusActivityScope.getDefault(_mActivity).post(new TabSelectedEvent(position));
            }
        });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == REQ_MSG && resultCode == RESULT_OK) {

        }
    }

    @Subscribe
    public void GoHomeEvent(GoHomeEvent event) {
        popTo(this.getClass(), false);
        mBottomBar.setCurrentItem(event.getIndex());
    }


//    @Subscribe
//    public void GoHomeEvent(GoMeEvent event) {
//        L.d("hcia", "MainFragment event:" + event);
//        popTo(this.getClass(), false);
//        mBottomBar.setCurrentItem(0);
//    }

    @Subscribe
    public void onTabSelectedEvent(SupportFragment event) {
//        L.d("hcia","event:"+event.position);


//        if (event instanceof ADOfficerRigisterFragment) {
//            extraTransaction()
////                        .setTag("CustomTag")
////                        . ...
//                    .setCustomAnimations(R.anim.v_fragment_enter, R.anim.v_fragment_pop_exit,
//                            R.anim.v_fragment_pop_enter, R.anim.v_fragment_exit)
//                    .start(event);
//            return;
//        }


        start(event);


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginEvent event) {

        if (event.getCode() != 10000)
            Toasty.info(getActivity(), event.getMsg()).show();

        if (event.getCode() == 401) {
//            ADLoginFragment.newInstance().show(getFragmentManager(), "");
//            CheckLoginDialog.newInstance().show(getFragmentManager(), "");

            if (findFragment(ADLoginFragment.class) == null && findChildFragment(ADLoginFragment.class) == null)
                start(ADLoginFragment.newInstance(), ISupportFragment.SINGLETOP);
        }

    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        L.d("hcia", "onDestroyView:");
        EventBusActivityScope.getDefault(_mActivity).unregister(this);
    }

    /**
     * start other BrotherFragment
     */
    public void startBrotherFragment(SupportFragment targetFragment) {
        start(targetFragment);
    }
}
